<?php
/* Reminder: always indent with 2 spaces (no tabs). */
// +---------------------------------------------------------------------------+
// | Nexfile for Drupal                                                        |
// +---------------------------------------------------------------------------+
// | Copyright (C) 2010 by the following authors:                              |
// | Blaine Lang - blaine DOT lang AT nextide DOT ca                           |
// +---------------------------------------------------------------------------+
// |                                                                           |
// | This program is free software; you can redistribute it and/or             |
// | modify it under the terms of the GNU General Public License               |
// | as published by the Free Software Foundation; either version 2            |
// | of the License, or (at your option) any later version.                    |
// |                                                                           |
// | This program is distributed in the hope that it will be useful,           |
// | but WITHOUT ANY WARRANTY; without even the implied warranty of            |
// | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the             |
// | GNU General Public License for more details.                              |
// |                                                                           |
// | You should have received a copy of the GNU General Public License         |
// | along with this program; if not, write to the Free Software Foundation,   |
// | Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.           |
// |                                                                           |
// +---------------------------------------------------------------------------+
// $Id$

/**
 * @file
 * lib-theme.php
 * Theme support functions for the module
 */




function template_preprocess_toolbar_form(&$variables) {
  global $base_url;
  $variables['report_option'] = 'latestfiles';
  $variables['base_url']       = $base_url;
  if (intval($_GET['cid']) > 0) {
    $variables['current_category'] = intval($_GET['cid']);
  }

}

function template_preprocess_header(&$variables) {
  global $nexfile;

  $variables['show_mainheader']     = '';
  $variables['show_incomingheader'] = 'none';
  $variables['LANG_filename'] = t('Filename');
  $variables['LANG_showfiledetails'] = t('Show File Details');
  $variables['LANG_expandfolders'] = t('Expand Folders');
  $variables['LANG_date'] = t('Date');
  $variables['LANG_folder'] = t('Folder');
  $variables['LANG_submitted'] = t('Submitted');
  $variables['LANG_owner'] = t('Owner');

  if ($nexfile->activeview == 'incoming') {
    $variables['show_incomingheader'] = '';
    $variables['show_mainheader'] = 'none';
  }

  if ($nexfile->cid > 0 OR $nexfile->activeview == 'approvals') {
    $variables['show_folder'] = 'none';
    $variables['show_folderexpandlink'] = '';
  } 
  else {
    $variables['show_folder'] = '';
    $variables['show_folderexpandlink'] = 'none';
  }

  if ($nexfile->activeview == 'approvals') {
    $variables['LANG_action'] = t('Submitter');
  } 
  else {
    $variables['LANG_action'] = t('Action');
  }

  if ($reportmode == 'incoming' AND user_access('administer nexfile', $user)) {
    $variables['show_owner'] = '';
  } 
  else {
    $variables['show_owner'] = 'none';
  }
}

function template_preprocess_folder_breadcrumb(&$variables) {
  if ($variables['cid'] > 0) {
    $foldername = db_result(db_query("SELECT name FROM {nexfile_categories} WHERE cid=%d", $variables['cid']));
    $variables['catid'] = $variables['cid'];
    $variables['padding_left'] = $variables['padding'];
    $variables['folder_name'] = filter_xss($foldername);
  }
}


function template_preprocess_activefolder_nonadmin(&$variables) {
  global $nexfile;

  $foldername = db_result(db_query("SELECT name FROM {nexfile_categories} WHERE cid=%d", $nexfile->cid));
  $variables['active_category_id'] = $nexfile->cid;
  $variables['active_folder_name'] = filter_xss($foldername);
  $variables['LANG_folderoptions'] = t('Folder Notification Options');
  $variables['LANG_newfiles'] = t('Alert me if new files are added');
  $variables['LANG_filechanges'] = t('Alert me if files are changed');
}

function template_preprocess_activefolder_admin(&$variables) {
  global $nexfile, $user;

  $variables['LANG_click_adminmsg'] = t('Click to edit folder options or administrate folder');
  $variables['LANG_parentfolder'] = t('Parent Folder');
  $variables['LANG_description'] = t('Description');
  $variables['LANG_folderorder'] = t('Folder Order');
  $variables['LANG_folderordermsg'] = t('Displayed in increments of 10 for easy editing');
  $variables['LANG_newfiles'] = t('Alert me if new files are added');
  $variables['LANG_filechanges'] = t('Alert me if files are changed');
  $variables['LANG_statsmsg'] = t('Stats that include this folder and all subfolders');
  $variables['LANG_foldercount'] = t('Folder Count');
  $variables['LANG_filecount'] = t('File Count');
  $variables['LANG_totalsize'] = t('Total Size');

  // Folder Stats
  $list = array();
  array_push($list, $nexfile->cid);
  nexdoc_getRecursiveCatIDs($list, $nexfile->cid, 'view');
  $variables['folder_count'] = count($list);
  $numfiles = 0;
  $totalsize = 0;
  foreach ($list as $folderid) {
    $q = db_query("SELECT count(fid) as filecount,sum(size) as filesize FROM {nexfile_files} WHERE cid=%d GROUP BY cid", $folderid);
    $A = db_fetch_array($q);
    $numfiles = $numfiles + $A['filecount'];
    $totalsize = $totalsize + $A['filesize'];
  }
  $variables['file_count'] = $numfiles;
  $variables['total_size'] = nexdoc_formatFileSize($totalsize);

  $A = db_fetch_array(db_query("SELECT pid,name,description,folderorder FROM {nexfile_categories} WHERE cid=%d", $nexfile->cid));
  $variables['folderorder'] = $A['folderorder'];
  $variables['active_category_id'] = $nexfile->cid;
  $variables['active_folder_name'] = filter_xss($A['name']);
  $variables['folder_description'] = filter_xss($A['description']);

  if ($A['pid'] == 0 OR user_access('administer nexfile', $user)) {
    $options = '<option value="0">' . t('Top Level Folder') . '</option>';
  }
  $options .= nexdoc_recursiveAccessOptions('admin', $A['pid']);
  $variables['folder_parent_options'] = $options;

  $query = db_query("SELECT cid_newfiles,cid_changes FROM {nexfile_notifications} WHERE cid=%d AND uid=%d", $nexfile->cid, $user->uid);
  if ($query) {
    $B = db_fetch_array($query);
    if ($B['cid_newfiles'] == 1) $variables['chk_fileadded'] = "CHECKED=checked";
    if ($B['cid_changes'] == 1) $variables['chk_filechanged'] = "CHECKED=checked";
  } 
  else {
    $variables['chk_fileadded'] = '';
    $variables['chk_filechanged'] = '';
  }

}


function template_preprocess_activefolder(&$variables) {
  global $base_url, $nexfile;

  $variables['show_activefolder'] = 'none';
  $variables['show_reportmodeheader'] = 'none';
  $variables['show_nonadmin'] = 'none';
  $variables['show_breadcrumbs'] = 'none';

  if ($nexfile->cid == 0) {
    if (in_array($nexfile->activeview, $nexfile->validReportingModes)) {
      $variables['report_heading'] = t('@heading', array('@heading' => $nexfile->activeview));
      $variables['show_reportmodeheader'] = '';
    }
  } 
  else {
    $variables['show_activefolder'] = '';
    $pid = db_result(db_query("SELECT pid FROM {nexfile_categories} WHERE cid=%d", $nexfile->cid));
    if ($pid != 0) {
      $parent = $pid;
      $rootfolder = $nexfile->cid;
      while ($parent != 0) {  // Determine the rootfolder
        $rootfolder = $parent;
        $parent = db_result(db_query("SELECT pid FROM {nexfile_categories} WHERE cid=%d", $parent));
      }
      $variables['folder_breadcrumb_links'] = theme('folder_breadcrumb', $rootfolder, 0);
      if ($rootfolder != $pid) {
        $query = db_query("SELECT cid from {nexfile_categories} WHERE cid=%d", $pid);
        $A = db_fetch_array($query);
        $variables['folder_breadcrumb_links'] .= theme('folder_breadcrumb', $A['cid'], 5);
      }
      $variables['show_breadcrumbs'] = 'block';
    }
    if ($nexfile->checkPermission($nexfile->cid, 'admin')) {
      $variables['active_folder_admin'] = theme('activefolder_admin');
    } 
    else {
      $variables['show_nonadmin'] = '';
      $variables['active_folder_admin'] = theme('activefolder_nonadmin');
    }
  }

  $variables['ajaxstatus'] = theme('ajaxstatus');
  $variables['ajaxactivity'] = theme('ajaxactivity', $variables['layout_url']);

}


function template_preprocess_folderlisting(&$variables) {
  global $nexfile, $base_url;

  $rec = $variables['folderrec'];      // cid,pid,name,description,folderorder,last_modified_date
  $level = $variables['level'];

  $variables['padding_right'] = 0;
  $variables['folder_desc_padding_left'] = 23 + (($level) * 30);   // Version 3.0 - not presently used
  $variables['folder_id'] = $rec['cid'];
  $variables['parent_folder_id'] = $rec['pid'];
  $variables['folder_name'] = filter_xss($rec['name']);
  $variables['folder_description'] = filter_xss($rec['description']);
  //$variables['folder_link'] = l('/nexfile/index.php',array('query' => array('cid' => $rec['cid'])));
  $variables['folder_contents'] = $variables['foldercontent'];
  $variables['folder_number'] = "{$variables['folderprefix']}.0";
  if ($rec['last_modified_date'] > 0) {
    $variables['last_modified_date'] = strftime($nexfile->shortdate, $rec['last_modified_date']);
  } 
  else {
    $variables['last_modified_date'] = '';
  }

  // For the checkall files - need to set the inline files
  // and can't be done in nexdoc_displayFileListing since a folder can have subfolders
  // and template var in parent folder is being over-written
  $query_files = db_query("SELECT fid from {nexfile_files} WHERE cid=%d", $rec['cid']);
  $files = array();
  while ($A = db_fetch_array($query_files)) {
    $files[] = $A['fid'];
  }
  $variables['folder_files'] = implode(',', $files);
  if ($nexfile->checkPermission($rec['cid'], 'admin')) {
    $variables['onhover_move_options'] = theme('folder_moveoptions', $rec['cid'], $rec['folderorder'], $variables['maxorder']);
  } 
  else {
    $variables['onhover_move_options'] = '';
  }
  $variables['folder_padding_left'] = $level * $nexfile->listingpadding;
}

function template_preprocess_folder_moveoptions(&$variables) {
  $variables['LANG_moveup'] = t('Move Folder Up');
  $variables['LANG_movedown'] = t('Move Folder Down');
  if ($variables['order'] == 10) {
    $variables['hide_moveup'] = 'none';
  } 
  else {
    $variables['hide_moveup'] = '';
  }
  if ($variables['order']  < $variables['maxorder']) {
    $variables['hide_movedown'] = '';
  } 
  else {
    $variables['hide_movedown'] = 'none';
  }  
}


function template_preprocess_filelisting(&$variables) {
  global $user, $nexfile, $nexcloud, $base_url;

  /* listing rec format
  file.fid as fid,file.cid,file.title,file.fname,file.date,file.version,file.submitter,file.status,
  detail.description,category.name as foldername,category.pid,category.last_modified_date,status_changedby_uid as changedby_uid, size
  */
  $rec = $variables['listingrec'];
  $level = $variables['level'];

  $variables['show_submitter'] = 'none';
  $variables['padding_left'] = ($level * $nexfile->listingpadding) + $nexfile->listingpadding;
  $variables['file_desc_padding_left'] = $nexfile->filedescriptionOffset + ($level * $nexfile->listingpadding);
  $variables['locked_icon'] = base_path() . drupal_get_path('module', 'nexfile') . '/css/images/' . $nexfile->getFileIcon('locked');
  if ($rec['status'] == 2) {
    $variables['show_lock'] = '';
  } 
  else  {
    $variables['show_lock'] = 'none';
  }
  $variables['details_link_parms'] = "?fid={$rec['fid']}";
  $variables['fid'] = $rec['fid'];
  $variables['filesize'] = nexdoc_formatFileSize($rec['fsize']);
  $variables['file_name'] = filter_xss($rec['title']);

  if (isset($rec['last_modified_date']) AND $rec['last_modified_date'] > 0) {
    $variables['modified_date'] = strftime($nexfile->shortdate, $rec['last_modified_date']);
  } 
  else {
    $variables['modified_date'] = strftime($nexfile->shortdate, $rec['date']);
  }

  $variables['folder_link'] = "{$base_url}/nexfile/index.php?cid={$rec['subfolderId']}";
  $variables['folder_name'] = filter_xss($rec['foldername']);
  $filenum = $variables['id'] + $nexfile->folder_filenumoffset;
  $variables['file_number'] = "{$variables['foldernumber']}.{$filenum}";
  $variables['subfolder_id'] = $rec['cid'];
  $variables['file_description'] = nl2br(filter_xss($rec['description']));

  $tags = $nexcloud->get_itemtags($variables['fid']);
  $variables['tags'] = nexdoc_formatfiletags($tags);

  $variables['show_favorite'] = 'none';
  if ($rec['status'] > 0 AND user_is_logged_in()) {
    $variables['show_favorite'] = '';
    if (db_result(db_query("SELECT count(fid) FROM {nexfile_favorites} WHERE uid=%d AND fid=%d", $user->uid, $variables['fid'])) > 0) {
      $variables['favorite_status_image'] = "{$variables['layout_url']}/css/images/{$nexfile->iconmap['favorite-on']}";
      $variables['LANG_favorite_status'] = t('Click to clear favorite');
    } 
    else {
      $variables['favorite_status_image'] = "{$variables['layout_url']}/css/images/{$nexfile->iconmap['favorite-off']}";
      $variables['LANG_favorite_status'] = t('Click to mark item as a favorite');
    }
  }

  if ($nexfile->activeview == 'approvals') {
    $variables['show_submitter'] = '';
    $variables['show_foldername'] = 'none';
    $variables['submitter'] = db_result(db_query("SELECT name FROM {users} WHERE uid=%d", $rec['submitter']));
  } 
  elseif ($nexfile->activeview == 'incoming') {
      $movelink = "<a class=\"moveincoming\" href=\"?fid={$rec['fid']}\" onClick=\"return false;\">" . t('Move') .'</a>';
      $deletelink = "<a class=\"deleteincoming\" href=\"?fid={$rec['fid']}\" onClick=\"return false;\">" . t('Delete') .'</a>';
      $variables['action1_link'] = $movelink;
      $variables['action2_link'] = $deletelink;
      $variables['submitter'] = db_result(db_query("SELECT name FROM {users} WHERE uid=%d", $rec['submitter']));         
      $variables['show_submitter'] = '';
      $variables['show_foldername'] = 'none';
  } 
  else {
    if ($nexfile->cid == 0 AND !empty($nexfile->activeview)) {
      $folder_admin = $nexfile->checkPermission($rec['subfolderId'], 'admin');
    } 
    else {
      $variables['show_foldername'] = 'none';
    }
    $variables['action1_link'] = '&nbsp;';
    $variables['action2_link'] = '&nbsp;';

    if (!$folder_admin AND $rec['status'] == NEXDOC_LOCKED_STATUS AND $rec['changedby_uid'] != $user->uid ) {  // File locked but not by user
      $downloadlinkimage = theme_image(drupal_get_path('module', 'nexfile') . '/css/images/' . $nexfile->getFileIcon('download'));
      $variables['action1_link'] =  l( $downloadlinkimage, "nexfile_download/{$rec['nid']}/{$rec['fid']}",
        array('html' => TRUE, 'attributes' => array('title' => t('Download File'))));
      $variables['action2_link'] = '';
    }
    else {
      $variables['action1_link'] = $downloadlink;
      $downloadlinkimage = theme_image(drupal_get_path('module', 'nexfile') . '/css/images/' . $nexfile->getFileIcon('download'));
      $variables['action1_link'] =  l( $downloadlinkimage, "nexfile_download/{$rec['nid']}/{$rec['fid']}",
        array('html' => TRUE, 'attributes' => array('title' => t('Download File'))));
      if ($user->uid > 0) {
        $editlinkimage = theme_image(drupal_get_path('module', 'nexfile') . '/css/images/' . $nexfile->getFileIcon('editfile'));
        $variables['action2_link'] =  l( $editlinkimage, "nexfile_download/{$rec['nid']}/{$rec['fid']}/0/edit",
          array('html' => TRUE, 'attributes' => array('title' => t('Download for Editing'))));
      }
      else {
        $variables['action2_link'] = '';
      }
    }

  }

  $icon = $nexfile->getFileIcon($rec['fname']);
  $variables['extension_icon'] = "{$variables['layout_url']}/css/images/$icon";
  if ($variables['morerecords'] == 'loadfolder_msg') {
    $variables['more_records_message'] = theme('filelisting_loadfolder', $rec['cid'], $variables['fid'], $variables['file_number'], $level);  
  } 
  elseif ($variables['morerecords'] != '') {
    $variables['more_records_message'] = theme('filelisting_moredata', $rec['cid'], $variables['fid'], $variables['file_number'], $level);  
  } 
  else {
    $variables['more_records_message'] = '';
  }

  
}

function template_preprocess_filelisting_moredata(&$variables) {
  global $nexfile;
  $variables['message_padding'] = 100 + ($variables['level'] * $nexfile->paddingsize);    
}

function template_preprocess_filelisting_loadfolder(&$variables) {
  global $nexfile;

  $variables['message_padding'] = 100 + ($variables['level'] * $nexfile->paddingsize);  
  
}



function template_preprocess_newfiledialog_folderoptions(&$variables) {
  $variables['folder_options'] = nexdoc_recursiveAccessOptions(array('upload', 'upload_dir'), $variables['cid']);
}

function template_preprocess_newfolderdialog(&$variables) {
  $variables['folder_options'] = nexdoc_recursiveAccessOptions('admin', $variables['cid']);
  $variables['LANG_folder'] = t('Folder Name');   
  $variables['LANG_description'] = t('Description');   
  $variables['LANG_inherit'] = t('Inherit Parent Permissions');   
  $variables['LANG_submit'] = t('Submit');   
  $variables['LANG_cancel'] = t('Cancel');   
  $variables['LANG_parentfolder'] = t('Parent Folder');   


}

function template_preprocess_movefiles_form(&$variables) {
  $variables['movefolder_options'] = nexdoc_recursiveAccessOptions('admin');
  $variables['LANG_newfolder'] = t('New Folder');
  $variables['LANG_submit'] = t('Submit');    
  $variables['LANG_cancel'] = t('Cancel');   
}

function template_preprocess_moveincoming_form(&$variables) {
  $variables['movefolder_options'] = nexdoc_recursiveAccessOptions('admin');
  $variables['LANG_newfolder'] = t('New Folder');    
  $variables['LANG_submit'] = t('Submit');    
  $variables['LANG_cancel'] = t('Cancel');    
}

function template_preprocess_filedetail(&$variables) {
  global $nexfile, $nexcloud;

  $fid = $variables['fid'];
  $variables['site_url']              = base_path();
  $variables['ajax_server_url']       = url('nexfile_ajax');
  $variables['LANG_tags'] = t('Tags');
  $variables['LANG_size'] = t('Size');
  $variables['LANG_author'] = t('Author');
  $variables['LANG_folder'] = t('Folder');
  $variables['LANG_description'] = t('Description');
  $variables['LANG_version_note'] = t('Version Note');
  $variables['LANG_download'] = t('Download File');
  $variables['LANG_link_message'] = t('Direct link to file');
  $variables['LANG_lastupated'] = t('Last Updated');

  if ($variables['reportmode'] == 'approvals') {
    $sql = "SELECT file.cid,file.title,file.fname,file.date,file.version,file.size, ";
    $sql .= "file.description,file.submitter,file.status,file.version_note as notes,tags ";
    $sql .= "FROM {nexfile_filesubmissions} file ";
    $sql .= "WHERE file.id=%d";
  }
  elseif ($variables['reportmode'] == 'incoming') {
    $sql = "SELECT 0,file.orig_filename as title,file.orig_filename as fname,file.timestamp,1,file.size, ";
    $sql .= "file.description,file.uid,9,file.version_note,'' ";
    $sql .= "FROM {nexfile_import_queue} file ";
    $sql .= "WHERE file.id=%d";
  }   
  else {
    $sql  = "SELECT file.cid, file.title, file.fname, file.date, file.version, file.size, ";
    $sql .= "file.description, file.submitter, file.status, v.notes, '' as tags ";
    $sql .= "FROM {nexfile_files} file ";
    $sql .= "LEFT JOIN {nexfile_fileversions} v ON v.fid=file.fid ";
    $sql .= "WHERE file.fid=%d ORDER BY v.version DESC LIMIT 1";
  }

  $filedetail = FALSE;
  $query = db_query($sql, $fid);
  $A = db_fetch_array($query);
  if ($A != NULL) {
    list($cid, $title, $fname, $date, $cur_version, $size, $description, $submitter, $status, $cur_notes, $tags) = array_values($A);
    $variables['cid'] = $cid;
    $variables['shortdate'] = strftime($nexfile->shortdate, $date);
    $variables['size'] = nexdoc_formatFileSize($size);
    $icon = $nexfile->getFileIcon($fname);
    $variables['fileicon'] = "{$variables['layout_url']}/css/images/$icon";

    $author = db_result(db_query("SELECT name FROM {users} WHERE uid=%d", $submitter));
    $catname = db_result(db_query("SELECT name FROM {nexfile_categories} WHERE cid=%d", $cid));
    $nid = db_result(db_query("SELECT nid FROM {nexfile_categories} WHERE cid=%d", $cid));
    $variables['fname'] = filter_xss($fname);
    $variables['current_version'] = "(V{$cur_version})";
    $variables['filetitle'] = filter_xss($title);
    $variables['author']  = $author;
    $variables['description'] = nl2br(filter_xss($description));
    $variables['foldername'] = filter_xss($catname);
    $variables['current_ver_note']= nl2br(filter_xss($cur_notes));
    $variables['tags'] = $nexcloud->get_itemtags($fid);

    if ($status == NEXDOC_UNAPPROVED_STATUS) {
      $variables['status_image'] = '<img src="'. $variables['layout_url'] . '/css/images/padlock.gif">';
      $variables['statusmessage'] = '* '.  t('File Submission to Approve');
    }
    elseif ($status == NEXDOC_INCOMING_STATUS) {
      $variables['status_image']   = '&nbsp;'; 
      $variables['statusmessage'] = '* '.  t('Incoming File - needs to be moved or deleted');
      $variables['disable_download'] = 'onClick="return false;"';      
    }
    elseif ($status == NEXDOC_LOCKED_STATUS) {
      $stat_userid = db_result(db_query("SELECT status_changedby_uid FROM {nexfile_files} WHERE fid=%d", $fid));
      $stat_user = db_result(db_query("SELECT name FROM {users} WHERE uid=%d", $stat_userid));
      $variables['status_image'] = '<img src="'. $variables['layout_url'] . '/css/images/padlock.gif">';
      $variables['statusmessage'] = '* ' . t('Locked by %name', array('%name' => $stat_user));
      $variables['LANG_DOWNLOAD_MESSAGE'] = t('File Locked by: %name', array('%name' => $stat_user));
      $variables['disable_download'] = 'onClick="return FALSE;"';
    } 
    else {
      $variables['show_statusmsg'] = 'none';
      $variables['status_image']   = '&nbsp;';
      $variables['statusmessage']  = '&nbsp;';
    }

    // Retrieve file versions
    $sql = "SELECT fid,fname,version,notes,size,date,uid FROM {nexfile_fileversions} "
    . "WHERE fid=%d AND version < %d ORDER by version DESC";
    $query = db_query($sql, $fid, $cur_version);
    $version_records = '';
    if ($query) {
      while ($rec = db_fetch_array($query)) {
        $rec['nid'] = $nid;
        $version_records .= theme('fileversion', $rec);
      }
    }
    $variables['version_records'] = $version_records;
  }

}


function template_preprocess_fileversion(&$variables) {
  global $nexfile;

  $variables['site_url']              = base_path();
  list($fid, $fname, $file_version, $ver_note, $ver_size, $ver_date, $submitter, $nid) = array_values($variables['versionRec']);

  $variables['LANG_version_note'] = t('Version Note');
  $variables['LANG_size'] = t('Size');
  $variables['LANG_download_message'] = t('Download Message');
  $variables['LANG_author'] = t('Author');
  $variables['LANG_download'] = t('Download File');
  $variables['LANG_edit'] = t('Edit File');
  $variables['LANG_delete'] = t('Delete File');
  $ver_shortdate = strftime($nexfile->shortdate, $ver_date);
  $ver_author = db_result(db_query("SELECT name from {users} WHERE uid=%d", $submitter));
  $icon = $nexfile->getFileIcon($fname);
  $variables['fileicon'] = "{$variables['layout_url']}/css/images/$icon";
  $variables['fid'] = $fid;
  $variables['nid'] = $nid;
  $variables['vname'] = filter_xss($fname);
  $variables['ver_shortdate'] = $ver_shortdate;
  $variables['ver_author'] = $ver_author;
  $variables['ver_size'] = nexdoc_formatFileSize($ver_size);
  $variables['ver_fileicon'] = $icon;
  $variables['file_versionnum'] = '(V' . $file_version . ')';
  $variables['file_version'] = $file_version;
  $variables['edit_version_note'] = filter_xss($ver_note);
  $variables['version_note'] = nl2br(filter_xss($ver_note));
  if ($nexfile->checkPermission($cid, 'admin')) {
    $variables['link_edit'] = '<a href="' . $_SERVER['PHP_SELF'] . '?op=editfile&fid=' . $fid . '&version=' . $file_version . '">' . t('Edit') . '</a>';
    $variables['link_delete'] = '<a href="' . $_SERVER['PHP_SELF'] . '?op=deletefile&fid=' . $fid . '&version=' . $file_version . '">' . t('Delete') . '</a>';
  }
  $variables['cssid'] = ($variables['zebra'] == 'odd') ? 1: 2;

}


function template_preprocess_folderperms(&$variables) {
  $variables['catid'] = $variables['cid'];
  $variables['user_options'] = nexdoc_getUserOptions();
  $variables['role_options'] = nexdoc_getRoleOptions();

  $variables['LANG_selectusers'] = t('Select Users');
  $variables['LANG_selectroles'] = t('Select Roles');
  $variables['LANG_accessrights'] = t('Access Rights');
  $variables['LANG_viewcategory'] = t('View Category');
  $variables['LANG_uploadapproval'] = t('Upload with Approval');
  $variables['LANG_uploadadmin'] = t('Upload Admin');
  $variables['LANG_uploaddirect'] = t('Upload Direct');
  $variables['LANG_categoryadmin'] = t('Category Admin');
  $variables['LANG_uploadversions'] = t('Upload New Versions');
  $variables['LANG_userrecords'] = t('User Access Records');
  $variables['LANG_rolerecords'] = t('Role Access Records');
  $variables['LANG_user'] = t('User');
  $variables['LANG_admin'] = t('Admin');
  $variables['LANG_action'] = t('Action');
  $variables['LANG_view'] = t('View');
  $variables['LANG_uploadadmin'] = t('Upload Admin');
  $variables['LANG_uploadversions'] = t('Upload Versions');
  $variables['LANG_directupload'] = t('Direct Upload');
  $variables['LANG_uploadwithapproval'] = t('Upload with Approval');


  $sql = "SELECT accid,permid,view,upload,upload_direct,upload_ver,approval,admin ";
  $sql .= "FROM {nexfile_access} WHERE permtype = 'user' AND permid > 0 AND catid = %d";
  $query = db_query($sql, $variables['cid']);
  while ($permrec = db_fetch_array($query)) {
    $user_perm_records .= theme('folderperm_rec', $permrec, 'user');
  }
  $variables['user_perm_records'] = $user_perm_records;

  $sql = "SELECT accid,permid,view,upload,upload_direct,upload_ver,approval,admin ";
  $sql .= "FROM {nexfile_access} WHERE permtype = 'role' AND permid > 0 AND catid = %d";
  $query = db_query($sql, $variables['cid']);
  while ($permrec = db_fetch_array($query)) {
    $role_perm_records .= theme('folderperm_rec', $permrec, 'role');
  }
  $variables['role_perm_records'] = $role_perm_records;

}


function template_preprocess_folderperm_rec(&$variables) {
  list($accid, $permid, $acc_view, $acc_upload, $acc_uploaddirect, $acc_uploadver, $acc_approval, $acc_admin) = array_values($variables['permRec']);
  if ($variables['mode'] == 'user') {
    $variables['name'] = db_result(db_query("SELECT name FROM {users} WHERE uid=%d", $permid));
  } 
  else {
    $variables['name'] = db_result(db_query("SELECT name FROM {role} WHERE rid=%d", $permid));
  }
  $variables['accid'] = $accid;
  $variables['view_perm'] = ($acc_view) ? t('Yes') : t('No');
  $variables['upload_perm'] = ($acc_upload) ? t('Yes') : t('No');
  $variables['uploaddir_perm'] = ($acc_uploaddirect) ? t('Yes') : t('No');
  $variables['uploadver_perm'] = ($acc_uploadver) ? t('Yes') : t('No');
  $variables['approve_perm'] = ($acc_approval) ? t('Yes') : t('No');
  $variables['admin_perm'] = ($acc_admin) ? t('Yes') : t('No');
  $variables['LANG_delete'] = t('Delete');
}


function template_preprocess_taglinkon(&$variables) {
  if (!empty($_POST['tags'])) {
    $variables['searchtag'] = strip_tags($_POST['tags']) . ',' . strip_tags($variables['searchtag']);
  }
}

function template_preprocess_searchtag(&$variables) {
  $variables['LANG_removetag'] = t('Remove search tag');
}


function template_preprocess_notifications_file(&$variables) {
  global $nexfile;

  $rec = $variables['rec'];
  $variables['recid'] = $rec['id'];
  $variables['fid'] = $rec['fid'];
  $variables['date'] = strftime($nexfile->shortdate, $rec['date']);
  $variables['LANG_delete'] = t('Delete');  

  $sql = "SELECT a.title,a.cid,b.name as folder FROM {nexfile_files} a ";
  $sql .= "LEFT JOIN {nexfile_categories} b ON b.cid = a.cid WHERE a.fid={$rec['fid']} ";
  list ($filename, $cid, $folder) = array_values(db_fetch_array(db_query($sql)));
  $variables['folderid'] = $cid;
  $variables['filename'] = filter_xss($filename);
  $variables['foldername'] = filter_xss($folder);

}

function template_preprocess_notifications_folder(&$variables) {
  global $nexfile;

  $rec = $variables['rec'];
  $variables['recid'] = $rec['id'];
  $variables['date'] = strftime($nexfile->shortdate, $rec['date']);
  $variables['folderid'] = $rec['cid'];
  $variables['LANG_delete'] = t('Delete');    
  if ($rec['cid_newfiles'] == 1)  {
    $variables['chk_newfiles'] = 'CHECKED=checked';
  } 
  else {
    $variables['chk_newfiles'] = '';
  }
  if ($rec['cid_changes'] == 1) {
    $variables['chk_filechanges'] = 'CHECKED=checked';
  } 
  else {
    $variables['chk_filechanges'] = '';
  }
  $folder = db_result(db_query("SELECT name FROM {nexfile_categories} WHERE cid=%d", $rec['cid']));
  $variables['foldername'] = filter_xss($folder);
}

function template_preprocess_notifications_history(&$variables) {
  global $nexfile, $base_url;

  $rec = $variables['rec'];
  $variables['notification_type'] = t('@type', array(
  '@type' => $nexfile->notificationTypes[$rec['notification_type']])
  );
  $variables['submitter_uid'] = $rec['submitter_uid'];
  $variables['submitter_name']= $rec['name'];
  $variables['file_name'] = filter_xss($rec['fname']);
  $foldername = db_result(db_query("SELECT name FROM {nexfile_categories} WHERE cid=%d", $rec['cid']));
  $variables['folder_name'] = filter_xss($foldername);
  $variables['fid'] = $rec['fid'];
  $variables['cid'] = $rec['cid'];
  $variables['notification_date'] = strftime('%b %d %y, %I:%M', $rec['datetime']);
  $variables['site_url'] = $base_url;   
}

function template_preprocess_notifications(&$variables) {
  global $user, $nexfile;

  $variables['LANG_yes'] = t('Yes');  
  $variables['LANG_no'] = t('No');    
  $variables['LANG_files_menuitem'] = t('Files');    
  $variables['LANG_folder_menuitem'] = t('Folders');    
  $variables['LANG_history_menuitem'] = t('Notification&nbsp;History');    
  $variables['LANG_settings_menuitem'] = t('Settings');    
  $variables['LANG_filename'] = t('File Name');  
  $variables['LANG_folder'] = t('Folder');
  $variables['LANG_dateadded'] = t('Date Added');  
  $variables['LANG_action'] = t('Action');  
  $variables['LANG_newfiles'] = t('New Files');  
  $variables['LANG_changes'] = t('Changes');  
  $variables['LANG_historymsg'] = t('Log of notification emails sent - max 100');  
  $variables['LANG_clearhistory'] = t('Clear History');  
  $variables['LANG_date'] = t('Date');  
  $variables['LANG_type'] = t('Type');  
  $variables['LANG_submitter'] = t('Submitter');  
  $variables['LANG_file'] = t('File');  
  $variables['LANG_norecords'] = t('No notification history on file');  
  $variables['LANG_savesettings'] = t('Save Settings');  
  $variables['LANG_settingheading'] = t('Setup your personal notification defaults. Individual folder and file notifications can also be used to over-ride these defaults.');  
  $variables['LANG_settingline1'] = t('If you want to be notified of all new new files being added for all folders you have access, then you only need to enable the setting here');  
  $variables['LANG_settingline2'] = t('If you only want to be notified of new files being added to selected folders, then disable the setting here and enable the notification for those selected folders only'); 
  $variables['LANG_settingline3'] = t('Folder Notification options are set by first selecting that folder and once the folder listing is in the main right panel, click on the folder name in the main right panel above the file listing to view/update the notification options');  
  $variables['LANG_settingline4'] = t('Broadcast Notifications can be sent out by folder administrators  even if you are not subscribed to updates unless you disable broadcasts here');  
  $variables['LANG_personalsettings'] = t('Personal Notification Setting');    
  $variables['LANG_default'] = t('Default');  
  $variables['LANG_newfilesadded'] = t('New Files being added');  
  $variables['LANG_yes'] = t('Yes');  
  $variables['LANG_no'] = t('No');  
  $variables['LANG_filesupdated'] = t('Files updated');  
  $variables['LANG_allowadminbroadcasts'] = t('Allow Admin Broadcasts'); 
  
  $sql = "SELECT a.id,a.fid,a.cid,a.date,cid_newfiles,cid_changes FROM {nexfile_notifications} a ";
  $sql .= "WHERE uid={$user->uid} AND a.ignore_filechanges = 0 ORDER BY a.date DESC";
  $query = db_query($sql);
  while ($A = db_fetch_array($query)) {
    if ($A['fid'] != 0) {
      $variables['file_records'] .= theme('notifications_file', $A);
    } 
    elseif ($A['cid'] > 0) {
      $variables['folder_records'] .= theme('notifications_folder', $A);
    }
  }

  if ($nexfile->notify_newfile) {
    $variables['chk_fileadded_on'] = 'CHECKED=checked';
  } 
  else {
    $variables['chk_fileadded_off'] = 'CHECKED=checked';
  }
  if ($nexfile->notify_changedfile) {
    $variables['chk_filechanged_on'] = 'CHECKED=checked';
  } 
  else {
    $variables['chk_filechanged_off'] = 'CHECKED=checked';
  }
  if ($nexfile->allow_broadcasts) {
    $variables['chk_broadcasts_on'] = 'CHECKED=checked';
  } 
  else {
    $variables['chk_broadcasts_off'] = 'CHECKED=checked';
  }

  $qsettings = db_query("SELECT * FROM {nexfile_usersettings} WHERE uid=%d", $user->uid);
  if ($qsettings) {
    $A = db_fetch_array($qsettings);
    if ($A['notify_newfile'] == 1) {
      $variables['chk_fileadded_off'] = '';
      $variables['chk_fileadded_on'] = 'CHECKED=checked';
    } 
    else {
      $variables['chk_fileadded_on'] = '';
      $variables['chk_fileadded_off'] = 'CHECKED=checked';
    }
    if ($A['notify_changedfile'] == 1) {
      $variables['chk_filechanged_off'] = '';
      $variables['chk_filechanged_on'] = 'CHECKED=checked';
    } 
    else {
      $variables['chk_filechanged_on'] = '';
      $variables['chk_filechanged_off'] = 'CHECKED=checked';
    }
    if ($A['allow_broadcasts'] == 1) {
      $variables['chk_broadcasts_off'] = '';
      $variables['chk_broadcasts_on'] = 'CHECKED=checked';
    } 
    else {
      $variables['chk_broadcasts_on'] = '';
      $variables['chk_broadcasts_off'] = 'CHECKED=checked';
    }
  }
  // Generate the user notification history - last 100 records
  $sql = "SELECT a.submitter_uid,a.notification_type,a.fid,b.fname,a.cid,c.name,a.datetime,d.name "
  . "FROM {nexfile_notificationlog} a "
  . "LEFT JOIN {nexfile_files} b ON b.fid=a.fid "
  . "LEFT JOIN {nexfile_categories} c ON c.cid=a.cid "
  . "LEFT JOIN {users} d ON d.uid=a.submitter_uid "
  . "WHERE a.target_uid={$user->uid} "
  . "ORDER BY a.datetime DESC LIMIT 100";
  $query = DB_query($sql);
  $cssid = 1;
  while ($A = db_fetch_array($query)) {
    $variables['history_records'] .= theme('notifications_history', $A);
  }
}

